const path = require("path");
const fs = require("fs");
const _ = require('lodash');

function resolve(dir) {
    return path.join(__dirname, '..', dir);
}
class MegerRouterPlugin {
    pluginName = 'MegerRouterPlugin'
    apply(compiler) {
        // 注册 before-compile 钩子，触发文件合并
        compiler.hooks.beforeCompile.tap(this.pluginName, compilation => {
            console.log("开始合并路由");
            // 最终生成的文件数据
            const data = {};
            const routesPath = resolve('src/routes');
            const targetFile = resolve('src/router-config.js');

            // 获取路径下所有的文件和文件夹
            const dirs = fs.readdirSync(routesPath);
            dirs.forEach(dir => {
                const routePath = resolve(`src/routes/${dir}`);
                // 判断是否是文件夹
                const routeInfo = require(routePath);
                console.log("routeInfo", routeInfo)
                routeInfo.forEach(route => {
                    data[route.url] = route.view;
                })
                console.log("data", data)
            });
            if (fs.existsSync(targetFile)) {
                delete require.cache[targetFile];
            }
            this.writeFile(targetFile, data);
        });
    }
    writeFile(targetFile, data) {
        console.log('writeFile', targetFile, data)
        fs.writeFileSync(targetFile, `module.exports = ${JSON.stringify(data, null, 2)}`, 'utf-8');
    }
}
module.exports = MegerRouterPlugin;
